package com.qf.filter;

import com.alibaba.fastjson.JSON;
import com.qf.entity.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;

@Component
public class QiangJuanFilter implements GatewayFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获得参数 - 抢卷的优惠卷id
        String cid = exchange.getRequest().getQueryParams().getFirst("cid");

        //判断当前id的优惠券是否开抢
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        hour = (hour % 2 == 0 ? hour : hour - 1);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        String goTimes = new SimpleDateFormat("yyMMddHH").format(calendar.getTime());

        //去redis中判断当前是否开抢
        Boolean flag = redisTemplate.opsForSet().isMember("qiangjuan_" + goTimes, cid);
        if (flag) {
            System.out.println("合法的优惠券领取请求！");
            //该优惠券可以参抢，直接放行
            return chain.filter(exchange);
        }

        //未获得令牌，则返回繁忙信息
        ServerHttpResponse response = exchange.getResponse();

        //当前优惠券未开抢
        R r = new R().setCode(R.Code.ERROR).setMsg("该优惠券不能抢购，请稍等！");
        DataBuffer dataBuffer = null;
        Mono<Void> voidMono = null;
        try {
            response.getHeaders().put("Content-Type", Collections.singletonList("application/json;charset=utf-8"));
            dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(r).getBytes("utf-8"));
            voidMono = response.writeWith(Mono.just(dataBuffer));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return voidMono;
    }

    /**
     * 优先级，数字越小，优先级越高，可以为负数
     * @return
     */
    @Override
    public int getOrder() {
        return 100;
    }
}
